//
//  SignUtil.swift
//  xz-app
//
//  Created by chen on 2025/5/6.
//
import SwiftUI
import CryptoKit

class SignUtil {
    
    /// 获取一个 32 位的随机字符串（由数字和字母组成）
    /// - Returns: 32 位随机字符串
    static func getRandom32BitString() -> String {
        var randomString = ""
        let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

        for _ in 0..<32 {
            let randomIndex = Int.random(in: 0..<characters.count)
            let character = characters[
                characters.index(characters.startIndex, offsetBy: randomIndex)
            ]
            randomString.append(character)
        }

        return randomString
    }
    
    static func getRandom6BitString() -> String {
        var randomString = ""
        let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

        for _ in 0..<6 {
            let randomIndex = Int.random(in: 0..<characters.count)
            let character = characters[
                characters.index(characters.startIndex, offsetBy: randomIndex)
            ]
            randomString.append(character)
        }

        return randomString
    }
    
    static func getSignature(nonceId:String, timestamp:String) -> String {
        let signStr = "nonce=" + nonceId + "&timestamp=" + timestamp;
        let md5String = signStr.md5
        return md5String.toBase64()
    }
    
    static func getDTKSignature(appKey: String, appSecret: String, timer: Int64, nonce: String) -> String {
        let signString = "appKey=\(appKey)&timer=\(timer)&nonce=\(nonce)&key=\(appSecret)"
        let md5String = signString.md5
        return md5String.uppercased()
    }
}
